package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"novel-start/models/cache"
	"novel-start/models/mysql"
	"time"

	"novel-start/novelrpc/internal/svc"
	"novel-start/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCommentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommentListLogic {
	return &CommentListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CommentListLogic) CommentList(in *novelrpc.CommentListRequest) (*novelrpc.CommentListResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if err := user.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}

	var commentList []*novelrpc.CommentList

	key := fmt.Sprintf("list%d", in.UserId)

	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		commentList = mysql.CommentList(mysql.DB, in, commentList)

		marshal, _ := json.Marshal(commentList)

		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*15)
	} else {
		json.Unmarshal([]byte(result), &commentList)
	}

	return &novelrpc.CommentListResponse{
		List: commentList,
	}, nil
}
